import sys
from xml.sax import make_parser, handler

class XMLTV(handler.ContentHandler):

    def __init__(self):
    	self.channels = {}
	self.currentChannel = None
	self.inDisplay = False

    def startElement(self, name, attrs):
        if (name == 'channel'):
            self.currentChannel = attrs['id']
        elif (name == 'display-name'):
            self.channels[self.currentChannel] = ''
	    self.inDisplay = True

    def endElement(self, name):
        if (name == 'channel'):
	    self.currentChannel = None
	elif (name == 'display-name'):
	    self.inDisplay = False

    def characters(self, ch):
        if (self.currentChannel != None and self.inDisplay):
	    self.channels[self.currentChannel] += ch

    def endDocument(self):
        for c in self.channels:
	    print c, self.channels[c]

    def __getitem__(self, key):
        """
        get method
        """
        return self.channels[key]

    def has_key(self, key):
        """
        has_key method
        """
        return self.channels.has_key(key)

    def keys(self):
        return self.channels.keys()

    def values(self):
        return self.channels.values()

    def parse(self, file):
        """
	Setup and do the parsing on this file
	"""
	parser = make_parser()
	parser.setContentHandler(self)
        parser.setFeature(handler.feature_validation, 0)
        parser.setFeature(handler.feature_namespaces, 0)
        parser.setFeature(handler.feature_external_pes, 0)
        parser.setFeature(handler.feature_external_ges, 0)
	parser.parse(file)


if __name__ == '__main__': 
    c = XMLTV()
    c.parse(sys.argv[1])

